package com.itheima.filter;

import com.itheima.config.BaseContext;
import com.itheima.pojo.Employee;
import jdk.nashorn.internal.runtime.options.LoggingOption;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import sun.rmi.runtime.Log;

import javax.lang.model.element.VariableElement;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author father
 * @date 2021/11/30
 * @apiNote
 **/
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
long id=Thread.currentThread().getId();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器线程id为 {}",id);
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        log.info("拦截到请求: {}", uri);
        if (uri.contains("login") || uri.endsWith(".js") || uri.endsWith(".css") || uri.contains("ico") || uri.endsWith(".png")||uri.contains("plugin")||uri.endsWith(".jpg")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        Employee employee = (Employee) req.getSession().getAttribute("employee");
        if (null != employee) {
            BaseContext.set(employee.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        resp.sendRedirect("/backend/page/login/login.html");
    }


}

